package com.net {

import com.fingerplay.main.model.Player;

import laya.events.Event;
import laya.net.HttpRequest;
import laya.utils.Handler;

public class GameHttpRequest extends HttpRequest {

	/** 请求数据完成 */
	private var completeHandler:Handler;
	/** 请求错误 */
	private var errorHandler:Handler;
	/** 超时 */
	private var timerOutHandler:Handler;
	/** 超时时间 */
	private var overtime:int = 10000;

	/**
	 * 一个请求
	 * @param completeHandler 请求结束
	 * @param errorHandler 请求错误
	 * @param timerOutHandler 请求超时
	 * @param overtime 超时时间
	 */
	public function GameHttpRequest(completeHandler:Handler, errorHandler:Handler=null, timerOutHandler:Handler=null, overtime:int=10000) {
		super();
		this.overtime = overtime;
		this.completeHandler = completeHandler;
		this.errorHandler = errorHandler;
		this.timerOutHandler = timerOutHandler;
		this.once(Event.COMPLETE, this, resultHandler);
		this.once(Event.ERROR, this, httpErrorHandler);
	}

	override public function send(url:String, data:* = null, method:String = "get", responseType:String = "text", headers:Array = null):void {
		if(overtime > 0) Laya.timer.once(overtime, this, timeOut);
		super.send(url, data, method, responseType, headers);
	}

	private function httpErrorHandler(obj:Object):void {
		Laya.timer.clear(this, timeOut);
		completeHandler.recover();
		timerOutHandler.recover();
		if(errorHandler) errorHandler.runWith(obj);
	}

	/** 请求返回结果数据 */
	private function resultHandler(json:Object):void {
		Laya.timer.clear(this, timeOut);
		errorHandler.recover();
		timerOutHandler.recover();
		if(completeHandler) completeHandler.runWith(json);
	}

	private function timeOut():void {
		Laya.timer.clear(this, timeOut);
		this.offAll(Event.COMPLETE);
		this.offAll(Event.ERROR);
		if (Player.inst.isWeb) this.http.abort();
		errorHandler.recover();
		completeHandler.recover();
		if(timerOutHandler) timerOutHandler.run();
	}

}
}
